package cn.rick.controller;

import cn.dev33.satoken.util.SaResult;
import cn.rick.entity.SysMenu;
import cn.rick.entity.SysRoleMenu;
import cn.rick.service.ISysMenuService;
import cn.rick.service.ISysRoleMenuService;
import cn.rick.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Rick
 * @date 2022-10-19 15:52
 */
@RestController
@RequestMapping("/api/menu")
@Api(value = "菜单控制", tags = {"菜单控制"})
public class MenuController {

    @Resource
    ISysMenuService iSysMenuService;

    @Resource
    ISysRoleMenuService iSysRoleMenuService;

    /**
     * 通过用户id查询菜单
     *
     * @param userId
     * @return
     */
    @GetMapping("/getMenu")
    @ApiOperation("通过用户id查询菜单")
    public SaResult selectAllByUserId(@RequestParam Long userId) {
        List<SysMenu> sysMenus = iSysMenuService.selectAllByUserId(userId);
        return SaResult.data(category0(sysMenus));
    }

    /**
     * 通过参数获取菜单列表
     *
     * @param sysMenu
     * @return
     */
    @GetMapping("/getDataByParams")
    @ApiOperation("通过参数获取菜单列表")
    public SaResult getDataByParams(SysMenu sysMenu) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(SysMenu::getOrderNum);
        if (StringUtils.isNotEmpty(sysMenu.getMenuName())) {
            queryWrapper.like(SysMenu::getMenuName, sysMenu.getMenuName());
        }
        if (StringUtils.isNotEmpty(sysMenu.getStatus())) {
            queryWrapper.eq(SysMenu::getStatus, sysMenu.getStatus());
        }
        List<SysMenu> sysMenus = iSysMenuService.list(queryWrapper);
        if (StringUtils.isNotEmpty(sysMenu.getMenuName()) || "1".equals(sysMenu.getStatus())) {
            return SaResult.data(sysMenus);
        } else {
            return SaResult.data(category0(sysMenus));
        }
    }

    @GetMapping("/getMenuIdsByRoleId")
    @ApiOperation("通过角色id查询菜单ids")
    public SaResult getMenuIdsByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> list = iSysRoleMenuService.list(queryWrapper);
        List<Long> listIds = new ArrayList<>();
        list.forEach(x -> {
            listIds.add(x.getMenuId());
        });
        return SaResult.data(listIds);
    }

    @PostMapping("/save")
    @ApiOperation("保存菜单信息")
    public SaResult save(@RequestBody SysMenu sysMenu) {
        if (iSysMenuService.saveOrUpdate(sysMenu)) {
            return SaResult.ok("保存成功");
        } else {
            return SaResult.error("保存失败，请稍后再试");
        }
    }

    @DeleteMapping("/del/{menuId}")
    @ApiOperation("删除菜单")
    public SaResult del(@PathVariable Long menuId) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId, menuId);
        List<SysMenu> list = iSysMenuService.list(queryWrapper);
        if (list.size() > 0) {
            return SaResult.error("此菜单还有[" + list.size() + "]个子菜单，无法删除");
        } else {
            if (iSysMenuService.removeById(menuId)) {
                return SaResult.ok("删除成功");
            } else {
                return SaResult.error("删除失败，请稍后再试");
            }
        }
    }

    public List<SysMenu> category0(List<SysMenu> sysMenus) {
        List<SysMenu> category0 = sysMenus.stream().filter(menu -> menu.getParentId() == 0).collect(Collectors.toList());
        category0.stream().forEach(category0Item -> {
            List<SysMenu> category1 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category0Item.getMenuId())).collect(Collectors.toList());
            category1.stream().forEach(category1Item -> {
                List<SysMenu> category2 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category1Item.getMenuId())).collect(Collectors.toList());
                category2.stream().forEach(category2Item -> {
                    List<SysMenu> category3 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category2Item.getMenuId())).collect(Collectors.toList());
                    category3.stream().forEach(category3Item -> {
                        List<SysMenu> category4 = sysMenus.stream().filter(menu -> menu.getParentId().equals(category3Item.getMenuId())).collect(Collectors.toList());
                        category3Item.setChildren(category4);
                    });
                    category2Item.setChildren(category3);
                });
                category1Item.setChildren(category2);
            });
            category0Item.setChildren(category1);
        });
        return category0;
    }

}
